package com.sdy.hospitalguard.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.hospitalguard.biz.constants.MqConstants;
import com.sdy.hospitalguard.biz.model.AccessControlTerminal;
import com.sdy.hospitalguard.biz.model.MatchingPeople;
import com.sdy.hospitalguard.biz.service.AccessControlTerminalService;
import com.sdy.hospitalguard.biz.utils.HttpReqUtil;
import com.sdy.mq.service.MqProducerService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.mvc.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.sdy.hospitalguard.biz.constants.UrlConstans.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-05-14
 */
@Slf4j
@Service
public class AccessControlTerminalServiceImpl extends BaseServiceImpl<AccessControlTerminal> implements AccessControlTerminalService {

    @Autowired
    private MqProducerService mqProducerService;

    @Override
    public List<AccessControlTerminal> getTerminal() {
        return list(new QueryWrapper<AccessControlTerminal>().eq("status", 0));
    }

    @Override
    public List<AccessControlTerminal> getTerminal(String building) {
        return list(new QueryWrapper<AccessControlTerminal>().eq("status", 0).eq("building", building));
    }

    @Override
    public void updateLibraries() throws BizException {
        List<AccessControlTerminal> list = getTerminal();
        Integer size = list.size();
        try {
            for (int i = 0; i < size; i++) {
                AccessControlTerminal accessControlTerminal = list.get(i);
                if (StringUtil.isBlank(accessControlTerminal.getLibrary())) {
                    String url = HTTP + accessControlTerminal.getIp() + SELECT_PEOPLE_LIBRARIES;
                    // 访问
                    String res = HttpReqUtil.get(url, "UTF-8", 30000, null);
                    JSONObject object = JSONObject.parseObject(res);
                    JSONObject response = object.getJSONObject("Response");
                    if (!(response.getInteger("StatusCode") == 0 && "Succeed".equals(response.getString("StatusString")))) {
                        Assert.isTrue(true, "默认访客库查询失败!");
                    }
                    JSONArray array = response.getJSONObject("Data").getJSONArray("LibList");
                    Integer library = null;
                    Integer arraySize = array.size();
                    for (int j = 0; j < arraySize; j++) {
                        Integer integer = array.getJSONObject(j).getInteger("Type");
                        if (integer == 4 && "默认访客库".equals(array.getJSONObject(j).getString("Name"))) {
                            library = array.getJSONObject(j).getInteger("ID");
                            break;
                        }
                    }
                    update(new UpdateWrapper<AccessControlTerminal>()
                            .eq("id", accessControlTerminal.getId())
                            .set("library", library));
                }
            }
        } catch (Exception e) {
            log.error("json解析失败", e);
        }
    }

    @Override
    public boolean addPerson(MatchingPeople matchingPeople) throws BizException {
        String s = new String(JsonUtil.serialize(matchingPeople));
        try {
            mqProducerService.send(MqConstants.Tags.TAG_ACCESS_ADD, s, true);
        }catch (Exception e) {
            log.error("", e);
            log.error("人员信息:{}", matchingPeople);
            return false;
        }
        return true;
        /*List<AccessControlTerminal> list = getTerminal(matchingPeople.getBuilding());
        //List<AccessControlTerminal> list = getTerminal();
        Integer size = list.size();
        try {
            for (int i = 0; i < size; i++) {
                AccessControlTerminal accessControlTerminal = list.get(i);
                // 出去的门禁设备不布控时间
                if (accessControlTerminal.getType() == 1) {
                    matchingPeople.setTimeTemplate(null);
                }
                String ip = accessControlTerminal.getIp();
                Integer library = accessControlTerminal.getLibrary();
                Assert.isNull(library, "门禁终端未进行初始化配置! 设备ip为:" + ip);
                String url = HTTP + ip + ADD_PERSON.replace("<ID>", library.toString());
                JSONObject request = new JSONObject(true);
                request.put("Num", 1);
                JSONArray personInfoList = new JSONArray();
                JSONObject personInfo = new JSONObject(true);
                personInfo.put("PersonID", matchingPeople.getUserId());
                personInfo.put("LastChange", matchingPeople.getLastChange());
                personInfo.put("PersonCode", matchingPeople.getUserId().toString());
                personInfo.put("PersonName", matchingPeople.getName());
                personInfo.put("Remarks", matchingPeople.getRemark());
                if (StringUtil.isBlank(matchingPeople.getTimeTemplate())) {
                    personInfo.put("TimeTemplateNum", 0);
                    personInfo.put("TimeTemplateList", "[{}]");
                } else {
                    String[] timeArray = matchingPeople.getTimeTemplate().split(",");
                    Integer length = timeArray.length;
                    personInfo.put("TimeTemplateNum", length);
                    JSONArray timeTemplateList = new JSONArray();
                    for (int j = 0; j < length; j++) {
                        JSONObject timeTemplate = new JSONObject(true);
                        timeTemplate.put("BeginTime", timeArray[j].split("-")[0]);
                        timeTemplate.put("EndTime", timeArray[j].split("-")[1]);
                        timeTemplate.put("Index", j);
                        timeTemplateList.add(timeTemplate);
                    }
                    personInfo.put("TimeTemplateList", timeTemplateList);
                }
                JSONArray identificationList = new JSONArray();
                Integer cardSize = 0;
                // 证件类型0:身份证 1:IC 卡99:其他
                if (StringUtil.isBlank(matchingPeople.getCardId()) && StringUtil.isBlank(matchingPeople.getCard())) {
                    cardSize = 0;
                } else if (StringUtil.isNotBlank(matchingPeople.getCardId()) && StringUtil.isNotBlank(matchingPeople.getCard())) {
                    cardSize = 2;
                    JSONObject cardIdJson = new JSONObject(true);
                    cardIdJson.put("Type", 0);
                    cardIdJson.put("Number", matchingPeople.getCardId());
                    identificationList.add(cardIdJson);
                    JSONObject cardJson = new JSONObject(true);
                    cardJson.put("Type", 1);
                    cardJson.put("Number", matchingPeople.getCard());
                    identificationList.add(cardJson);
                } else {
                    cardSize = 1;
                    if (StringUtil.isNotBlank(matchingPeople.getCardId())) {
                        JSONObject cardIdJson = new JSONObject(true);
                        cardIdJson.put("Type", 0);
                        cardIdJson.put("Number", matchingPeople.getCardId());
                        identificationList.add(cardIdJson);
                    } else {
                        JSONObject cardJson = new JSONObject(true);
                        cardJson.put("Type", 1);
                        cardJson.put("Number", matchingPeople.getCard());
                        identificationList.add(cardJson);
                    }
                }
                personInfo.put("IdentificationNum", cardSize);
                personInfo.put("IdentificationList", identificationList);
                String ptohoPath = matchingPeople.getPhotoPath();
                JSONArray imageList = new JSONArray();
                JSONObject image = new JSONObject(true);
                String base64s = "";
                if (StringUtil.isBlank(ptohoPath)) {
                    personInfo.put("ImageNum", 0);
                } else {
                    base64s = PdfUtils.readFileToBase64(ptohoPath);
                    personInfo.put("ImageNum", 1);
                    image.put("FaceID", matchingPeople.getFaceId());
                    image.put("Name", ptohoPath.substring(ptohoPath.lastIndexOf("/")));
                    image.put("Data", base64s);
                    image.put("Size", base64s.length());
                }
                imageList.add(image);
                personInfo.put("ImageList", imageList);
                personInfoList.add(personInfo);
                request.put("PersonInfoList", personInfoList);
                String res = HttpReqUtil.postJson(url, request.toString(), "UTF-8", "UTF-8", 30000, null);
                JSONObject object = JSONObject.parseObject(res);
                JSONObject response = object.getJSONObject("Response");
                if (!(response.getInteger("StatusCode") == 0 && "Succeed".equals(response.getString("StatusString")))) {
                    return false;
                }
                JSONArray array = response.getJSONObject("Data").getJSONArray("PersonList")
                        .getJSONObject(0).getJSONArray("FaceList");
                if (0 == array.getJSONObject(0).getInteger("ResultCode")) {

                } else if (1010 == array.getJSONObject(0).getInteger("ResultCode")) {
                    log.warn("ResultCode:" + array.getJSONObject(0).getInteger("ResultCode") + "导入图片不存在，无法进行人脸识别");
                } else {
                    log.error("ResultCode:" + array.getJSONObject(0).getInteger("ResultCode") +
                            "。userId:" + matchingPeople.getUserId() + "。building:" + matchingPeople.getBuilding());
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("json解析失败", e);
            return false;
        }
        return true;*/
    }

    @Override
    public boolean updatePerson(MatchingPeople matchingPeople) throws BizException {
        return addPerson(matchingPeople);
    }

    @Override
    public boolean deletePerson(MatchingPeople matchingPeople) throws BizException {
        // 0为不删除出门门禁设备的数据，1为删除
        String s = new String(JsonUtil.serialize(matchingPeople));
        try {
            mqProducerService.send(MqConstants.Tags.TAG_ACCESS_DELETE, "0" + s, true);
        }catch (Exception e) {
            log.error("", e);
            log.error("人员信息:{}", matchingPeople);
            return false;
        }
        return true;
        /*List<AccessControlTerminal> list = getTerminal(matchingPeople.getBuilding());
        //List<AccessControlTerminal> list = getTerminal();
        Integer size = list.size();
        try {
            for (int i = 0; i < size; i++) {
                // 出去的门禁设备不删除人
                AccessControlTerminal accessControlTerminal = list.get(i);
                if (accessControlTerminal.getType() == 1) {

                } else {
                    String ip = accessControlTerminal.getIp();
                    Integer library = accessControlTerminal.getLibrary();
                    Assert.isNull(library, "门禁终端未进行初始化配置! 设备ip为:" + ip);
                    String url = HTTP + ip + DELETE_PERSON.replace("<PD>", library.toString())
                            .replace("<ID>", matchingPeople.getUserId().toString()).replace("<LastChange>", matchingPeople.getLastChange());
                    String res = HttpReqUtil.delete(url, "UTF-8", 30000, null);
                    JSONObject object = JSONObject.parseObject(res);
                    JSONObject response = object.getJSONObject("Response");
                    if (!(response.getInteger("StatusCode") == 0 && "Succeed".equals(response.getString("StatusString")))) {
                        log.warn("当前终端：{}，无此人PersonID={}", accessControlTerminal.getSign(), matchingPeople.getUserId());
                    }
                }
            }
        } catch (Exception e) {
            log.error("json解析失败", e);
            return false;
        }
        return true;*/
    }

    @Override
    public boolean deletePerson(MatchingPeople matchingPeople, Integer type) throws BizException {
        // 0为不删除出门门禁设备的数据，1为删除
        String s = new String(JsonUtil.serialize(matchingPeople));
        try {
            mqProducerService.send(MqConstants.Tags.TAG_ACCESS_DELETE, "1" + s, true);
        }catch (Exception e) {
            log.error("", e);
            log.error("人员信息:{}", matchingPeople);
            return false;
        }
        return true;
    }

    @Override
    public AccessControlTerminal getAccess(String sign) {
        QueryWrapper<AccessControlTerminal> wrapper = new QueryWrapper<>();
        wrapper.eq("sign", sign);
        AccessControlTerminal accessControlTerminal = getOne(wrapper);
        return accessControlTerminal;
    }

    @Override
    public boolean selectPersonId(String cardId, Integer building) throws BizException{
        List<AccessControlTerminal> list = getTerminal(building.toString());
        Integer size = list.size();
        Integer personId = 0;
        for (int i = 0; i < size; i++) {
            AccessControlTerminal accessControlTerminal = list.get(i);
            if (accessControlTerminal.getType() == 1) {
                String ip = accessControlTerminal.getIp();
                Integer library = accessControlTerminal.getLibrary();
                if (library == null) {
                    log.error("门禁终端未进行初始化配置! 设备ip为:" + ip);
                    log.error("cardId：{}", cardId);
                    return false;
                }
                String url = HTTP + ip + SELECT_PERSON.replace("<ID>", library.toString());
                JSONObject request = new JSONObject(true);
                // 查询条件数量,0则获取所有人员信息
                request.put("Num", 1);
                JSONArray queryInfosArray = new JSONArray();
                JSONObject queryInfoObject = new JSONObject(true);
                // 查询条件,27：员工编号，55：人员姓名，58：证件号
                queryInfoObject.put("QryType", 58);
                queryInfoObject.put("QryCondition", 0);
                queryInfoObject.put("QryData", cardId);
                queryInfosArray.add(queryInfoObject);
                request.put("QueryInfos", queryInfosArray);
                request.put("Limit", 6);
                request.put("Offset", 0);
                String res = HttpReqUtil.postJson(url, request.toString(), "UTF-8",
                        "UTF-8", 30000, null);
                JSONObject object = JSONObject.parseObject(res);
                JSONObject response = object.getJSONObject("Response");
                if (!(response.getInteger("StatusCode") == 0 && "Succeed".equals(response.getString("StatusString")))) {
                    log.error("默认访客库查询失败!");
                    return false;
                }
                Integer total = response.getJSONObject("Data").getInteger("Total");
                if (total == 0) {
                    personId = 0;
                }
                if (total != 1) {
                    log.error("error,查询结果不唯一,数量为：{}", total);
                    return false;
                }
                JSONArray array = response.getJSONObject("Data").getJSONObject("PersonList").getJSONArray("PersonInfoList");
                personId =  array.getJSONObject(0).getInteger("PersonID");
                long lastChange = array.getJSONObject(0).getLong("LastChange");
                // 删除人员
                if (personId == 0) {

                } else {
                    String urlSecond = HTTP + ip + DELETE_PERSON.replace("<PD>", library.toString())
                            .replace("<ID>", personId.toString()).replace("<LastChange>", String.valueOf(lastChange));
                    String result = HttpReqUtil.delete(urlSecond, "UTF-8", 30000, null);
                    JSONObject objectRseult = JSONObject.parseObject(result);
                    JSONObject responseRseult = objectRseult.getJSONObject("Response");
                    if (!(responseRseult.getInteger("StatusCode") == 0 && "Succeed".equals(responseRseult.getString("StatusString")))) {
                        log.warn("当前终端：{}，无此人PersonID={}", accessControlTerminal.getSign(), personId);
                    }
                    log.info("删除原有身份证数据成功。sfz：{}", cardId);
                }
            }
        }
        return true;
    }

}
